package utils;

import com.mchange.v2.c3p0.ComboPooledDataSource;

import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

/*
    定义C3P0Util工具类,从C3P0连接池中获取连接Connection对象
 */
public class C3P0Util {
    //创建C3P0连接池的对象,内部存储了多个Connection对象
    //创建对象时,会自动读取src根目录下的配置文件,怎么读取的,不用关心
    private static ComboPooledDataSource cpds = new ComboPooledDataSource();

    private C3P0Util(){

    }
    //定义静态方法,获取Connection对象
    public static Connection getConnection() throws SQLException {
        //连接池对象,调用getConnection()方法,获取连接Connection对象
        return cpds.getConnection();
    }
    //定义静态方法,获取连接池对象
    public static DataSource getDataSource() {
        return cpds;
    }

    //释放资源
    public static void release(Connection con, Statement stmt, ResultSet rs) {
        //4.关闭资源
        if(con!=null) {
            try {
                con.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
        if(stmt!=null) {
            try {
                stmt.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
        if(rs!=null) {
            try {
                rs.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
    }

}
